package com.ikkong.api;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.ikkong.api.model.BaseResponse;
import com.ikkong.api.model.Code;
import com.ikkong.api.model.DataResponse;
import com.ikkong.api.util.Require;
import com.ikkong.common.vo.User;
import com.ikkong.core.base.BaseController;
import com.ikkong.platform.model.Member;
import com.jfinal.aop.Clear;
import com.ikkong.api.intercept.*;



import java.lang.reflect.Array;
import java.util.List;

import javax.xml.ws.spi.http.HttpContext;
import com.ikkong.api.TokenManager;
/**
 * 基本的api
 * 基于jfinal controller做一些封装
 */
@Clear
public class BaseAPIController extends BaseController {

	 /**
     * 获取当前用户对象
     * @return
     */
    protected Member getUser() {
    	Member user = getAttr("user");
        if (user == null) {
            String token = getPara("token");
            return StringUtils.isEmpty(token) ? null : TokenManager.getMe().validate(token);
        }
        return getAttr("user");
    }
    /**
     * 响应接口不存在*
     */
    public void render404() {

        renderJson(new BaseResponse(Code.NOT_FOUND));
        
    }

    /**
     * 响应请求参数有误*
     * @param message 错误信息
     */
    public void renderArgumentError(String message) {

        renderJson(new BaseResponse(Code.ARGUMENT_ERROR, message));

    }

    /**
     * 响应数组类型*
     * @param list 结果集合
     */
    public void renderDataResponse(List<?> list) {
        DataResponse resp = new DataResponse();
        resp.setData(list);
        if (list == null || list.size() == 0) {
            resp.setMessage("未查询到数据");
        } else {
            resp.setMessage("success");
        }
        renderJson(resp);
        
    }

    /**
     * 响应操作成功*
     * @param message 响应信息
     */
    public void renderSuccess(String message) {
        renderJson(new BaseResponse().setMessage(message));
        
    }

    /**
     * 响应操作失败*
     * @param message 响应信息
     */
    public void renderFailed(String message) {
        renderJson(new BaseResponse(Code.FAIL, message));
        
    }
    

    /**
     * 响应操作失败*
     * @param message 响应信息
     */
    public void renderError(String message) {
        renderJson(new BaseResponse(Code.ERROR, message));
        
    }
    
    /**
     * 判断请求类型是否相同*
     * @param name
     * @return
     */
    protected boolean methodType(String name) {
        return getRequest().getMethod().equalsIgnoreCase(name);
    }
    
    
    /**
     * 判断请求类型是否相同*
     * @param name
     * @return
     */
    protected void setHeader() {
    	getResponse().addHeader("Access-Control-Allow-Origin","*");
		getResponse().addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
    }
    
    protected  String Output(Object ob){
    	String cb=getRequest().getParameter("callback");
    	String result="";
    	if(StringUtils.isEmpty(cb)){
    		 result=JSONObject.toJSONString(ob);
    	}else{
			result=cb+"("+JSONObject.toJSONString(ob)+")";
    	}
    	return result;
    	
    }
    
    /**
     * 判断参数值是否为空
     * @param rules
     * @return
     */
    public boolean notNull(Require rules) {

        if (rules == null || rules.getLength() < 1) {
            return true;
        }

        for (int i = 0, total = rules.getLength(); i < total; i++) {
            Object key = rules.get(i);
            String message = rules.getMessage(i);
            BaseResponse response = new BaseResponse(Code.ARGUMENT_ERROR);
            
            if (key == null) {
                renderJson(response.setMessage(message));
                return false;
            }

            if (key instanceof String && StringUtils.isEmpty((String) key)) {
                renderJson(response.setMessage(message));
                return false;
            }

            if (key instanceof Array) {
                Object[] arr = (Object[]) key;

                if (arr.length < 1) {
                    renderJson(response.setMessage(message));
                    return false;
                }
            }
        }

        return true;
    }
    
    /**
     * @param urlAll
     *            :请求接口
     * @param httpArg
     *            :参数
     * @return 返回结果
     */
/*    public static String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            // 填入apikey到HTTP header
            connection.setRequestProperty("apikey",  "a84cab502bc270daa1e178507243e30f");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }*/
}
